package com.fy56.platform.logistics.redis.dao.impl;

import com.fy56.platform.logistics.model.Token;
import com.fy56.platform.logistics.redis.dao.AbstractBaseRedisDao;
import com.fy56.platform.logistics.redis.dao.ITokenDao;
import com.fy56.platform.logistics.redis.dbutil.TokenConstants;
import org.springframework.stereotype.Repository;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by li on 2018-02-06 10:40
 */
@Repository
public class TokenDaoImpl extends AbstractBaseRedisDao implements ITokenDao  {

    @Override
    public Token createToken(long userId) {
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        Token model = new Token(userId, token);
        //存储到redis并设置过期时间
        redisUtils.set(String.valueOf(userId),token, TokenConstants.TOKEN_EXPIRES_SECONDS, TimeUnit.SECONDS);
        return model;
    }

    @Override
    public Token getToken(String authentication) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        //使用userId和源token简单拼接成的token，可以增加加密措施
        long userId = Long.parseLong(param[0]);
        String token = param[1];
        return new Token(userId, token);
    }

    @Override
    public boolean checkToken(Token model) {
        if (model == null) {
            return false;
        }
        Object token = redisUtils.get(String.valueOf(model.getUserId()));
        if (token == null || !token.equals(model.getToken())) {
            return false;
        }
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
        redisUtils.expire(String.valueOf(model.getUserId()),TokenConstants.TOKEN_EXPIRES_SECONDS, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void deleteToken(long userId) {
        redisUtils.del(String.valueOf(userId));
    }


}
